/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package wf.ui;

import bc.dsl.PageDSL;
import bc.dsl.SwingDSL;
import bc.swing.models.chart.BarChartModel;
import bc.swing.models.chart.ChartModel;
import bc.swing.models.chart.PieChartModel;
import bc.swing.pfrm.Model;
import bc.swing.pfrm.ano.Action;
import bc.swing.pfrm.ano.PageDef;
import bc.swing.pfrm.ano.Param;
import bc.swing.pfrm.ano.ViewHints;
import bc.swing.pfrm.layouts.FormLayout;
import bc.swing.pfrm.models.NoDataModel;
import bc.swing.pfrm.viewtypes.ParamType;
import java.awt.Color;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
import javax.swing.JPanel;
import wf.model.Counter;
import wf.model.Statistic;
import wf.ui.layouts.StatisticsLayout;
import wf.units.DatabaseUnit;

/**
 *
 * @author bennyl
 */
@PageDef(name = "Statistics Manager", layout = StatisticsLayout.class, icon = "statistics")
public class StatisticsManager extends Model {

    public static final String CURRENT_CHART_PARAM = "Current Chart";
    SupportedStatistics selectedStatistic;
    StatisticFilter filter;
    ChartModel currentChart = null;

    public StatisticsManager() {
        selectedStatistic = SupportedStatistics.GENERAL_WATER_CONSUMPTION;
        filter = new StatisticFilter();
    }

    @Param(name = CURRENT_CHART_PARAM, type = ParamType.CHART, role = StatisticsLayout.CHART_PAGE_ROLE)
    public ChartModel getCurrentChart() {
        return currentChart;
    }

    @ViewHints(foreground = {255, 255, 255})
    @Param(name = "Available Statistics", type = ParamType.RADIO_GROUP, role = StatisticsLayout.AVAILABLE_STATISTICS_ROLE)
    public SupportedStatistics getAvailableStatistics() {
        return selectedStatistic;
    }

    public void setAvailableStatistics(SupportedStatistics availableStatistics) {
        this.selectedStatistic = availableStatistics;
    }

    @Param(name = "Filter", type = ParamType.PAGE, role = StatisticsLayout.FILTERS_PAGE_ROLE)
    public StatisticFilter getFilter() {
        return filter;
    }

    @Action(name = "Generate Chart", icon = "chart-gen22")
    void handleGenerateChart() {
        syncFromView();

        switch (selectedStatistic) {
            case GENERAL_WATER_CONSUMPTION:
                generateGeneralWaterConsumption();
                break;
            case WATER_CONSUMPTION_BY_SINGLE_COUNTER:
                generateWaterConsumptionBySingleCounter();
                break;
        }
    }

    public static void main(String[] args) {
        SwingDSL.configureUI();
        DatabaseUnit.UNIT.connect();
        PageDSL.showInFrame(new StatisticsManager());
    }

    private void generateGeneralWaterConsumption() {
        List<Statistic> list = DatabaseUnit.UNIT.collectGeneralWaterConsumptionStatistics(
                filter.getStartDate().getTime(),
                filter.getEndData().getTime(),
                filter.getResolution());

        PieChartModel c = new PieChartModel();
        for (Statistic l : list) {
            c.set(l.getCounterName(), l.getWaterConsumption());
        }

        c.setTitle("General Water Consumption");

        this.currentChart = c;
        syncToView(CURRENT_CHART_PARAM);
    }

    private void generateWaterConsumptionBySingleCounter() {
        List<Statistic> list = DatabaseUnit.UNIT.collectWaterStatisticsBySingleCounter(
                filter.getStartDate().getTime(),
                filter.getEndData().getTime(),
                filter.getResolution(),
                filter.getSelectedCounter().getId());

        BarChartModel c = new BarChartModel();
        SimpleDateFormat sdf = filter.resolution.getFormatter();
        for (Statistic l : list) {
            c.set(sdf.format(l.getDate()), l.getWaterConsumption());
        }

        c.setTitle("Water Consumption By Counter " + filter.getSelectedCounter().getName());
        c.setDomainAxisLabel("");
        c.setRangeAxisLabel("Water Consumption (Liters)");

        this.currentChart = c;
        syncToView(CURRENT_CHART_PARAM);
    }

    @PageDef(name = "Statistic Filter", layout = FormLayout.class)
    public static class StatisticFilter extends Model {

        Calendar startDate;
        Calendar endData;
        StatisticsResolution resolution;
        List<Counter> counters;

        public StatisticFilter() {
            startDate = Calendar.getInstance();
            startDate.add(Calendar.MONTH, -1);
            endData = Calendar.getInstance();
            resolution = StatisticsResolution.MONTH;
            counters = DatabaseUnit.UNIT.selectAllCounters();
        }

        @Override
        public void configurePageLayout(JPanel layout) {
            ((FormLayout) layout).setColorLabels(false);
            ((FormLayout) layout).setLabelsForeground(Color.white);
        }

        @Param(name = "Start Date", type = ParamType.DATE_AND_TIME, num = 0)
        public Calendar getStartDate() {
            return startDate;
        }

        @Param(name = "End Date", type = ParamType.DATE_AND_TIME, num = 1)
        public Calendar getEndData() {
            return endData;
        }

        public void setStartDate(Calendar startDate) {
            this.startDate = startDate;
        }

        public void setEndData(Calendar endData) {
            this.endData = endData;
        }

        @Param(name = "Data Resolution", type = ParamType.OPTIONS, num = 2)
        public StatisticsResolution getResolution() {
            return resolution;
        }

        @Param(name = "Counter", type = ParamType.OPTIONS, num = 3)
        public List<Counter> getCounters() {
            return counters;
        }

        public void setResolution(StatisticsResolution resolution) {
            this.resolution = resolution;
        }

        public Counter getSelectedCounter() {
            return (Counter) getPage().getParam("Counter").getSelectedItem();
        }
    }

    public static enum StatisticsResolution {

        DAY("Day", "'%Y %m %d'", "dd.MM.yy"),
        WEEK("Week", "'%Y %m %U'", "yyyy 'week:'ww"),
        MONTH("Month", "'%Y %m'", "M'.'yyyy"),
        YEAR("Year", "'%Y'", "yyyy");
        String tos;
        String sqlFilter;
        SimpleDateFormat viewFormat;

        private StatisticsResolution(String tos, String sqlFilter, String viewDateFormat) {
            this.tos = tos;
            this.sqlFilter = sqlFilter;
            this.viewFormat = new SimpleDateFormat(viewDateFormat);
        }

        @Override
        public String toString() {
            return tos;
        }

        public String getSqlFilter() {
            return sqlFilter;
        }

        public SimpleDateFormat getFormatter() {
            return viewFormat;
        }
    }

    public static enum SupportedStatistics {

        GENERAL_WATER_CONSUMPTION("General Water Consumption"),
        //WATER_CONSUMPTION_BY_COUNTERS("Water Consumption By Counters"),
        WATER_CONSUMPTION_BY_SINGLE_COUNTER("Water Consumption By Counter");
        String tos;

        private SupportedStatistics(String tos) {
            this.tos = tos;
        }

        @Override
        public String toString() {
            return tos;
        }
    }
}
